package com.xindaoapp.happypet.fragments;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.bean.InteralBanner;
import com.xindaoapp.happypet.bean.InteralList;
import com.xindaoapp.happypet.ui.MyRecordActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.RollViewPager3;

/**
 * 兑换中心
 * 
 * @author Administrator
 * 
 */
public class ChangeCenterFragment extends BaseFragment {

    private ScheduledExecutorService scheduledExecutor;
    private TextView mTitle;
    private ImageView mBackView;
    private TextView vMoreNiu;
    private ListView mlistview;
    /** 轮播图 */
    private LinearLayout mViewPager;
    private TextView mtvDescription;
    private LinearLayout mllPoints;

    private LinearLayout vViewpage;
    private TextView vDescription;

    private List<InteralBanner> mBanners;

    private final boolean isRunning = false;
    private int lastPointIndex = 0;
    private int currentItem;

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {

            // 指定当前页面
            vp.setCurrentItem(currentItem);
        };
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_change_center, container, false);
    }

    @Override
    protected void initViews(View view) {
        vMoreNiu = (TextView) view.findViewById(R.id.moreniuniu);
        vNiuniu = (TextView) view.findViewById(R.id.niuniubi);
        mRmb = (ImageView) view.findViewById(R.id.rmb);
        mlistview = (ListView) view.findViewById(R.id.changelist);

        // mlistview.setMode(PullToRefreshBase.Mode.BOTH);
        LayoutInflater inflater =
                (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewpager = inflater.inflate(R.layout.layout_change_item, null);
        vViewpage = (LinearLayout) viewpager.findViewById(R.id.top_change_viewpager);
        vDescription = (TextView) viewpager.findViewById(R.id.top_change_title);
        // mllPoints = (LinearLayout) viewpager.findViewById(R.id.dots_ll);


        vChangeViewPager = inflater.inflate(R.layout.change_viewpage, null);
        vp = (ViewPager) vChangeViewPager.findViewById(R.id.viewpager);
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new MyPagerTask(), 2, 3, TimeUnit.SECONDS);
        mllPoints = (LinearLayout) vChangeViewPager.findViewById(R.id.ll_points1);

        super.initViews(view);
    }

    private void isUserLogin() {
        if (UserState.getUser() != null) {
            vNiuniu.setText(UserState.getUser().niuniu);
            vMoreNiu.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    if (UserState.isLogged(getActivity())) {
                        // Intent intent = new Intent(mActivity, MainActivity.class);
                        // intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        // IntegralFragment.class.getCanonicalName());
                        // mActivity.startActivity(intent);
                        // startFragment(new IntegralFragment());

                        Intent intent2 = new Intent(mActivity, MyRecordActivity.class);
                        mActivity.startActivity(intent2);
                    }
                }
            });
        } else {
            mRmb.setVisibility(View.INVISIBLE);
            vNiuniu.setVisibility(View.INVISIBLE);
            vMoreNiu.setText("登录");
            vMoreNiu.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Intent intent = new Intent(mActivity, MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            LoginFragment.class.getCanonicalName());
                    mActivity.startActivityForResult(intent, Constants.REQUESTCODE_LOGIN);
                }
            });
        }
    }

    private void initList() {
        getMoccaApi().getChangeList(new IRequest<List<InteralList>>() {

            @Override
            public void request(List<InteralList> t) {
                if (t != null) {
                    mlistview.setAdapter(new MyAdapter(t));
                }
            }

        });

    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    protected void initEvents() {
        super.initEvents();
    }

    public List<InteralBanner> lists = null;



    @Override
    protected String getTitleName() {
        return "兑换中心";
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        // getBannerData();
        isUserLogin();
        getMoccaApi().getChangePager(new IRequest<List<InteralBanner>>() {


            @Override
            public void request(List<InteralBanner> t) {
                lists = t;
                if (lists != null) {
                    // prepareViewPage(list);
                    vp.setAdapter(new MyPagerAdapter(lists));
                    initDots(lists.size());
                }
                // mlistview.addHeaderView(viewpager);
                mlistview.addHeaderView(vChangeViewPager);
                initList();
            }

        });

        vp.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                int myIndex = position % lists.size();
                // 将当前指示点的图片enable设为true
                mllPoints.getChildAt(myIndex).setEnabled(true);
                // 将上一个指示点设置为false
                mllPoints.getChildAt(lastPointIndex).setEnabled(false);
                lastPointIndex = myIndex;

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }


    private ArrayList<View> dotLists;
    private RollViewPager3 rollViewPager;
    private View viewpager;
    private ViewPager vp;
    private View vChangeViewPager;
    private TextView vNiuniu;
    private ImageView mRmb;

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        mllPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            // LinearLayout.LayoutParams layoutParams =
            // new LinearLayout.LayoutParams(CommonUtil.dip2px(mActivity, 10),
            // CommonUtil.dip2px(mActivity, 10));
            // layoutParams.setMargins(5, 0, 5, 0);
            // // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // // 15);
            //
            // // lp.leftMargin = 10;
            //
            // View m = new View(mActivity);
            // if (i == 0) {
            // m.setBackgroundResource(R.drawable.point_enable);
            // } else {
            // m.setBackgroundResource(R.drawable.point_normal);
            // }
            // m.setLayoutParams(layoutParams);
            // dotLists.add(m);
            // mllPoints.addView(m);

            // 添加指示点
            ImageView point = new ImageView(mActivity);
            point.setBackgroundResource(R.drawable.point_background);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, -2);
            params.leftMargin = 15;
            point.setLayoutParams(params);

            mllPoints.addView(point);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }

        }
    }

    class MyAdapter extends BaseAdapter {

        List<InteralList> list;
        int num = 0;

        // List<InteralList> list1;
        // List<InteralList> list2;

        public MyAdapter(List<InteralList> t) {
            super();
            list = t;
            // list1 = t1;
            // list1 = t1;
        }

        @Override
        public int getCount() {
            if (list.size() % 2 == 0) {
                return num = list.size() / 2;
            } else {
                return num = list.size() / 2 + 1;
            }
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public boolean isEnabled(int position) {
            return false;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup arg2) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mActivity, R.layout.item_changecenter, null);
                holder.img1 = (ImageView) convertView.findViewById(R.id.img1);
                holder.img2 = (ImageView) convertView.findViewById(R.id.img2);
                holder.title1 = (TextView) convertView.findViewById(R.id.title1);
                holder.jifen1 = (TextView) convertView.findViewById(R.id.jifen1);
                holder.title2 = (TextView) convertView.findViewById(R.id.title2);
                holder.jifen2 = (TextView) convertView.findViewById(R.id.jifen2);
                holder.ll1 = (LinearLayout) convertView.findViewById(R.id.ll1);
                holder.ll2 = (LinearLayout) convertView.findViewById(R.id.ll2);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.img1.setScaleType(ScaleType.FIT_XY);
            holder.img2.setScaleType(ScaleType.FIT_XY);
            if (num == position + 1 && list.size() % 2 == 1) {
                ImageLoader.getInstance().displayImage(list.get(position * 2).goods_thumb,
                        holder.img1);
                holder.ll1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(mActivity, MainActivity.class);
                        intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                ChangeDescFragment.class.getCanonicalName());
                        Bundle bundle = new Bundle();
                        bundle.putString("ex_id", list.get(position * 2).ex_id + "");
                        intent.putExtra(Constants.KEY_BUNDLE, bundle);
                        mActivity.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                    }
                });
            } else {
                ImageLoader.getInstance().displayImage(list.get(position * 2).goods_thumb,
                        holder.img1);
                holder.title1.setText(list.get(position * 2).goods_name);
                holder.jifen1.setText(list.get(position * 2).exchange_integral);
                ImageLoader.getInstance().displayImage(list.get((position * 2) + 1).goods_thumb,
                        holder.img2);
                holder.title2.setText(list.get((position * 2) + 1).goods_name);
                holder.jifen2.setText(list.get((position * 2) + 1).exchange_integral);
                holder.ll1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(mActivity, MainActivity.class);
                        intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                ChangeDescFragment.class.getCanonicalName());
                        Bundle bundle = new Bundle();
                        bundle.putString("ex_id", list.get(position * 2).ex_id + "");
                        intent.putExtra(Constants.KEY_BUNDLE, bundle);
                        mActivity.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                    }
                });
                holder.ll2.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(mActivity, MainActivity.class);
                        intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                ChangeDescFragment.class.getCanonicalName());
                        Bundle bundle = new Bundle();
                        bundle.putString("ex_id", list.get((position * 2) + 1).ex_id + "");
                        intent.putExtra(Constants.KEY_BUNDLE, bundle);
                        mActivity.startActivity(intent);
                        // startFragment(new ChangeDescFragment(), bundle);
                    }
                });
            }



            // img1.setImageResource();
            // img2.setImageResource(R.drawable.all292);
            return convertView;
        }
    }

    class ViewHolder {
        private LinearLayout ll1;
        private LinearLayout ll2;
        private ImageView img1;
        private ImageView img2;
        private TextView title1;
        private TextView jifen1;
        private TextView title2;
        private TextView jifen2;
    }


    class MyPagerAdapter extends PagerAdapter {

        List<InteralBanner> list;

        public MyPagerAdapter(List<InteralBanner> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 获得指定位置的view
            ImageView iv = new ImageView(mActivity);
            iv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT));
            iv.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(list.get(position % list.size()).coverpath, iv);
            // 将view 添加至container
            container.addView(iv);
            return iv;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    private class MyPagerTask implements Runnable {

        @Override
        public void run() {
            // 切换图片
            currentItem = currentItem + 1;
            handler.sendEmptyMessage(0);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        // onLoadData();
        isUserLogin();
    }
}
